###########重定向#################
# from flask import Flask , render_template,request,redirect
# from vowel import search4letters

# app = Flask(__name__)

# @app.route('/')
# def hello()->'302':
#     return redirect('/entry')

# @app.route('/search4',methods=['POST'])
# def do_search()->'html':
#     phrase = request.form['phrase']
#     letters = request.form['letters']
#     title = 'here are your results:'
#     results = str(search4letters(phrase,letters)) 
#     return render_template('results.html',
#         the_title=title,
#         the_results=results,
#         the_phrase=phrase,
#         the_letters=letters)

# @app.route('/entry')
# def entry_page():
#     return render_template('entry.html',the_title='Welcome to search4letters on the web')

# app.run(debug=True)

##################一个函数可以有多个Url ###########

from flask import Flask , render_template,request,escape
from vowel import search4letters

app = Flask(__name__)

def log_request(req:'flask_request',res:str)->None:
    #定义连接属性
    dbconfig={'host':'127.0.0.1',
	      'user':'vsearch',
	      'password':'woshibyl',
	      'database':'vsearchlogDB'}
    #导入驱动程序
    import mysql.connector
    #建立一个连接
    conn=mysql.connector.connect(**dbconfig)
    #建立一个游标
    cursor=conn.cursor()
    #创建一个字符串包含你想要的查询
    _sql="""insert into log
            (phrase,letters,ip,browser_string,results)
            values
            (%s,%s,%s,%s,%s)"""
    #执行这个查询
    cursor.execute(_sql,(req.form['phrase'],
                        req.form['letters'],
                        req.remote_addr,
                        req.user_agent.browser,
                        res,))#req.user_agent.browser只抽取浏览器名，不再是整个浏览器串
    #强制将所有缓存数据写入数据库表
    conn.commit()
    #关闭游标和连接进行清理
    cursor.close()
    conn.close()
    

@app.route('/search4',methods=['POST'])
def do_search()->'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'here are your results:'
    results = str(search4letters(phrase,letters)) 
    log_request(request,results)
    return render_template('results.html',
        the_title=title,
        the_results=results,
        the_phrase=phrase,
        the_letters=letters)

@app.route('/')
@app.route('/entry')
def entry_page():
    return render_template('entry.html',the_title='Welcome to search4letters on the web')

@app.route('/viewlog')
def view_log()->'html':
        contents = []
        with open('vsearch.log') as log:
                # contents = log.readlines()
                for i in log:
                        contents.append([])
                        for j in i.split('|'):
                                contents[-1].append(escape(j))
        titles = ('form data','remote_addr','user_agent','results')
        return render_template('viewlog.html',
        the_title='view log',
        the_row_titles=titles,
        the_data=contents,)
if __name__ == "__main__":
    app.run(debug=True)





